import { CrudOptions, AddReq, DelReq, EditReq, dict, CrudExpose, UserPageQuery, CreateCrudOptionsRet } from '@fast-crud/fast-crud';
import * as api from './api';
import { computed, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { auth } from "/@/utils/authFunction";

interface BudgetRow {
    id: string;
    status: 'pending' | 'approved' | 'rejected';
    can_edit: boolean;
    can_approve: boolean;
    can_reject: boolean;
    can_delete: boolean;
}

export default function ({ crudExpose }: { crudExpose: CrudExpose }): CreateCrudOptionsRet {
    const pageRequest = async (query: any) => {
        return await api.GetList(query);
    };
    
    const editRequest = async ({ form, row }: EditReq) => {
        if (row.id) {
            form.id = row.id;
        }
        return await api.UpdateObj(form);
    };
    
    const delRequest = async ({ row }: DelReq) => {
        return await api.DelObj(row.id);
    };
    
    const addRequest = async ({ form }: AddReq) => {
        return await api.AddObj(form);
    };

    const exportRequest = async (query: UserPageQuery) => {
        return await api.exportData(query)
    };

    const showEdit = ref((ctx: any) => ctx.row.status === 'pending');
    const showApprove = ref((ctx: any) => ctx.row.status === 'pending');
    const showReject = ref((ctx: any) => ctx.row.status === 'pending');
    const showDelete = ref((ctx: any) => ctx.row.status === 'pending');

    return {
        crudOptions: {
            request: {
                pageRequest,
                addRequest,
                editRequest,
                delRequest,
            },
            form: {
                beforeSubmit({ form }) {
                    if (form.amount !== undefined) {
                        form.amount = Number(form.amount);
                    }
                    return true;
                }
            },
            actionbar: {
                buttons: {
                    export: {
                        show: auth('finance:budget:export'),
                        text: "导出",
                        title: "导出",
                        click() {
                            return exportRequest(crudExpose.getSearchFormData())
                        }
                    },
                    add: {
                        show: auth('finance:budget:create'),
                    },
                }
            },
            rowHandle: {
                fixed: 'right',
                width: 280,
                buttons: {
                    view: {
                        link: true,
                        text: '查看',
                        icon: 'View',
                        type: 'info',
                        order: 1,
                        style: { fontSize: '14px', marginRight: '8px' },
                        show: auth('finance:budget:retrieve'),
                        click: ({ row }) => {
                            crudExpose.getFormRef()?.open('view', row);
                        }
                    },
                    edit: {
                        link: true,
                        text: '编辑',
                        icon: 'Edit',
                        type: 'primary',
                        order: 2,
                        style: { fontSize: '14px', marginRight: '8px' },
                        show: auth('finance:budget:update'),
                        hidden: ({ row }: { row: BudgetRow }) => {
                            return row.status !== 'pending';
                        }
                    },
                    approve: {
                        link: true,
                        text: '通过',
                        icon: 'Check',
                        type: 'success',
                        order: 3,
                        style: { fontSize: '14px', marginRight: '8px' },
                        show: auth('finance:budget:approve'),
                        hidden: ({ row }: { row: BudgetRow }) => {
                            return row.status !== 'pending';
                        },
                        click: async ({ row }: { row: BudgetRow }) => {
                            ElMessageBox.confirm(
                                '确定要通过该预算申请吗？',
                                '审批确认',
                                {
                                    confirmButtonText: '确定',
                                    cancelButtonText: '取消',
                                    type: 'warning',
                                }
                            ).then(async () => {
                                await api.approveObj(row.id);
                                ElMessage.success('审批通过成功');
                                crudExpose.doRefresh();
                            }).catch(() => {
                                // 取消操作，不做任何处理
                            });
                        }
                    },
                    reject: {
                        link: true,
                        text: '拒绝',
                        icon: 'Close',
                        type: 'danger',
                        order: 4,
                        style: { fontSize: '14px', marginRight: '8px' },
                        show: auth('finance:budget:reject'),
                        hidden: ({ row }: { row: BudgetRow }) => {
                            return row.status !== 'pending';
                        },
                        click: async ({ row }: { row: BudgetRow }) => {
                            ElMessageBox.confirm(
                                '确定要拒绝该预算申请吗？',
                                '拒绝确认',
                                {
                                    confirmButtonText: '确定',
                                    cancelButtonText: '取消',
                                    type: 'warning',
                                }
                            ).then(async () => {
                                await api.rejectObj(row.id);
                                ElMessage.success('已拒绝该预算申请');
                                crudExpose.doRefresh();
                            }).catch(() => {
                                // 取消操作，不做任何处理
                            });
                        }
                    },
                    remove: {
                        link: true,
                        text: '删除',
                        icon: 'Delete',
                        type: 'danger',
                        order: 5,
                        style: { fontSize: '14px' },
                        show: auth('finance:budget:delete'),
                        hidden: ({ row }: { row: BudgetRow }) => {
                            return row.status !== 'pending';
                        }
                    },
                },
            },
            columns: {
                title: {
                    title: '预算标题',
                    type: 'input',
                    search: {
                        show: true,
                        component: {
                            props: {
                                clearable: true,
                                placeholder: '请输入预算标题'
                            }
                        }
                    },
                    column: {
                        minWidth: 160,
                        sortable: 'custom',
                    },
                    form: {
                        rules: [{ required: true, message: '预算标题必填' }],
                        component: {
                            placeholder: '请输入预算标题'
                        }
                    },
                },
                amount: {
                    title: '预算金额',
                    type: 'number',
                    search: { show: false },
                    column: {
                        minWidth: 120,
                        sortable: 'custom',
                    },
                    form: {
                        rules: [{ required: true, message: '预算金额必填' }],
                        component: {
                            name: 'el-input-number',
                            props: {
                                precision: 2,
                                step: 1000,
                                min: 0,
                                placeholder: '请输入预算金额',
                                controlsPosition: 'right'
                            }
                        },
                        valueBuilder({ form }) {
                            if (form.amount !== undefined && form.amount !== null) {
                                form.amount = Number(form.amount);
                            }
                        }
                    },
                },
                department: {
                    title: '申请部门',
                    type: 'dict-select',
                    dict: dict({
                        url: '/api/budget/get_departments/',
                        value: 'key',
                        label: 'name',
                        cache: false,
                        immediate: true
                    }),
                    search: {
                        show: true,
                        component: {
                            name: 'fs-dict-select',
                            props: {
                                clearable: true,
                                filterable: true,
                                placeholder: '请选择申请部门'
                            }
                        }
                    },
                    column: {
                        minWidth: 120,
                        component: {
                            name: 'fs-dict-select',
                            props: {
                                disabled: true
                            }
                        }
                    },
                    form: {
                        rules: [{ required: true, message: '申请部门必填' }],
                        component: {
                            name: 'fs-dict-select',
                            props: {
                                clearable: true,
                                filterable: true,
                                placeholder: '请选择申请部门'
                            }
                        }
                    }
                },
                purpose: {
                    title: '用途说明',
                    type: 'textarea',
                    column: {
                        minWidth: 200,
                    },
                    form: {
                        rules: [{ required: true, message: '用途说明必填' }],
                    },
                },
                create_datetime: {
                    title: '创建时间',
                    type: 'date',
                    search: {
                        show: true,
                        component: {
                            name: 'el-date-picker',
                            props: {
                                type: 'date',
                                valueFormat: 'YYYY-MM-DD',
                                format: 'YYYY-MM-DD',
                                clearable: true,
                                placeholder: '请选择创建日期'
                            }
                        }
                    },
                    column: {
                        width: 180,
                        sortable: 'custom',
                        component: {
                            name: 'fs-date-format',
                            props: {
                                format: 'YYYY-MM-DD HH:mm:ss'
                            }
                        }
                    },
                    form: {
                        show: false
                    }
                },
                status: {
                    title: '审批状态',
                    type: 'dict-select',
                    dict: dict({
                        data: [
                            { value: 'pending', label: '待审批', color: '#E6A23C' },
                            { value: 'approved', label: '已通过', color: '#67C23A' },
                            { value: 'rejected', label: '已拒绝', color: '#F56C6C' }
                        ]
                    }),
                    search: { show: true },
                    column: {
                        width: 100,
                        align: 'center',
                        formatter: ({ row }: { row: BudgetRow }) => {
                            const statusMap: Record<string, { text: string; type: string }> = {
                                pending: { text: '待审批', type: 'warning' },
                                approved: { text: '已通过', type: 'success' },
                                rejected: { text: '已拒绝', type: 'danger' }
                            };
                            const status = statusMap[row.status] || { text: row.status, type: 'info' };
                            return <el-tag size="small" type={status.type}>{status.text}</el-tag>;
                        }
                    },
                    form: {
                        show: false
                    }
                },
            },
            table: {
                show: true,
                scroll: { fixed: true }
            }
        },
    };
}